package com.czk.api.createtable;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/2 15:01
 */
public class CreateTableApi {
    private static Connection connection = null;
    private static Admin admin = null;

    static {
        // 静态代码块初始化
        // 创建配置类
        Configuration configuration = HBaseConfiguration.create();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        //
        try {
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 关闭连接
     */
    public static void close() {
        try {
            if (admin != null) {
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        createTable("0408:stu5", "info1", "info2");
        System.out.println(tableExists("stu5"));
    }


    /**
     * 创建表
     *
     * @param tableName 表名
     * @param args      可变参数
     * @throws IOException
     */
    public static void createTable(String tableName, String... args) throws IOException {
        // 判断是否存在列族信息
        if (args.length <= 0) {
            //
            System.out.println("设置列族信息");
            return;
        }
        // 判断表是否存在
        if (tableExists(tableName)) {
            System.out.println("tableName=" + tableName + "已经存在");
            return;
        }
        // 创建表
        HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
        for (String arg : args) {
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(arg);
            // 循环添加列族
            descriptor.addFamily(hColumnDescriptor);
        }
        // 创建表
        admin.createTable(descriptor);
    }

    /**
     * 判断表是否存在
     *
     * @param tableName
     * @return
     * @throws IOException
     */
    private static boolean tableExists(String tableName) throws IOException {
        return admin.tableExists(TableName.valueOf(tableName));
    }
}
